<!-- 试卷管理 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="试卷名称">
          <el-input
            v-model="queryParams.keyword"
            placeholder="试卷名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目">
          <el-input
            v-model="queryParams.subject"
            placeholder="科目"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="toolbar-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="success" @click="handleGeneratePaper">
          <el-icon><Document /></el-icon>
          规则生成
        </el-button>
      </div>
    </div>

    <!-- 试卷列表 -->
    <el-table v-loading="loading" :data="paperList" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column
        prop="paperName"
        label="试卷名称"
        show-overflow-tooltip
      />
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column prop="totalScore" label="总分" width="80" />
      <el-table-column prop="duration" label="时长(分钟)" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'info'">
            {{ row.status === 0 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="success" link @click="handleViewQuestions(row)">
            查看题目
          </el-button>
          <el-button
            :type="row.status === 0 ? 'warning' : 'success'"
            link
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 0 ? "禁用" : "启用" }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="paperFormRef"
        :model="paperForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="paperName">
          <el-input
            v-model="paperForm.paperName"
            placeholder="请输入试卷名称"
          />
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="paperForm.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="paperForm.totalScore" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="duration">
          <el-input-number v-model="paperForm.duration" :min="1" :max="180" />
        </el-form-item>
        <el-form-item label="规则配置" prop="ruleConfig">
          <el-input
            v-model="paperForm.ruleConfig"
            type="textarea"
            rows="4"
            placeholder="请输入规则配置，JSON格式"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 规则生成对话框 -->
    <el-dialog
      title="规则生成试卷"
      v-model="generateDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="generateRules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="paperName">
          <el-input
            v-model="generateForm.paperName"
            placeholder="请输入试卷名称"
          />
        </el-form-item>
        <el-form-item label="规则" prop="ruleId">
          <el-select
            v-model="generateForm.ruleId"
            placeholder="请选择规则"
            style="width: 100%"
          >
            <el-option
              v-for="rule in ruleList"
              :key="rule.id"
              :label="rule.ruleName"
              :value="rule.id"
            >
              <span>{{ rule.ruleName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ rule.subject }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="generateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleGenerateSubmit"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 查看题目对话框 -->
    <el-dialog
      title="试卷题目"
      v-model="questionsDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-table :data="questionList" style="width: 100%">
        <el-table-column prop="questionType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.questionType === 'single' ? 'primary' : 'success'"
            >
              {{ row.questionType === "single" ? "单选题" : "多选题" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="questionText"
          label="题目内容"
          show-overflow-tooltip
        />
        <el-table-column prop="score" label="分值" width="80" />
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficulty)">
              {{ row.difficulty }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getPapers,
  addPaper,
  updatePaper,
  deletePaper,
  updateStatus,
  getPaperQuestions,
  generatePaper,
} from "@/api/exam";
import { getRules } from "@/api/rule";
import { Search, Plus, Refresh, Document } from "@element-plus/icons-vue";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  subject: "",
});

// 试卷列表数据
const loading = ref(false);
const paperList = ref([]);
const total = ref(0);

// 规则列表数据
const ruleList = ref([]);

// 获取规则列表
const getRuleList = async () => {
  try {
    const { records } = await getRules({ pageSize: 999 });
    ruleList.value = records;
  } catch (error) {
    console.error("获取规则列表失败：", error);
  }
};

// 规则生成相关
const generateDialogVisible = ref(false);
const generateFormRef = ref(null);
const generateForm = reactive({
  paperName: "",
  ruleId: null,
});

const generateRules = {
  paperName: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
  ruleId: [{ required: true, message: "请选择规则", trigger: "change" }],
};

// 打开规则生成对话框
const handleGeneratePaper = () => {
  generateForm.paperName = "";
  generateForm.ruleId = null;
  generateDialogVisible.value = true;
};

// 提交规则生成
const handleGenerateSubmit = async () => {
  if (!generateFormRef.value) return;

  await generateFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await generatePaper(generateForm);
        ElMessage.success("试卷生成成功");
        generateDialogVisible.value = false;
        getPaperList();
      } catch (error) {
        ElMessage.error(error.message || "试卷生成失败");
      }
    }
  });
};

// 获取试卷列表
const getPaperList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getPapers(queryParams);
    paperList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取试卷列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getPaperList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.keyword = "";
  queryParams.subject = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getPaperList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getPaperList();
};

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = computed(() => (paperForm.id ? "编辑试卷" : "新增试卷"));
const paperFormRef = ref(null);
const paperForm = reactive({
  id: null,
  paperName: "",
  subject: "",
  totalScore: 100,
  duration: 60,
  ruleConfig: "",
});

// 表单校验规则
const rules = {
  paperName: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  totalScore: [{ required: true, message: "请输入总分", trigger: "blur" }],
  duration: [{ required: true, message: "请输入时长", trigger: "blur" }],
  ruleConfig: [{ required: true, message: "请输入规则配置", trigger: "blur" }],
};

// 重置表单
const resetForm = () => {
  paperForm.id = null;
  paperForm.paperName = "";
  paperForm.subject = "";
  paperForm.totalScore = 100;
  paperForm.duration = 60;
  paperForm.ruleConfig = "";
};

// 新增按钮点击
const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = (row) => {
  Object.assign(paperForm, row);
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!paperFormRef.value) return;
  await paperFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 验证 ruleConfig 是否为有效的 JSON
        try {
          JSON.parse(paperForm.ruleConfig);
        } catch (e) {
          ElMessage.error("规则配置必须是有效的 JSON 格式");
          return;
        }

        if (paperForm.id) {
          await updatePaper(paperForm);
          ElMessage.success("更新成功");
        } else {
          await addPaper(paperForm);
          ElMessage.success("添加成功");
        }
        dialogVisible.value = false;
        getPaperList();
      } catch (error) {
        console.error("保存试卷失败：", error);
      }
    }
  });
};

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该试卷吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deletePaper(row.id);
        ElMessage.success("删除成功");
        getPaperList();
      } catch (error) {
        console.error("删除试卷失败：", error);
      }
    })
    .catch(() => {});
};

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    await updateStatus(row.id, row.status === 0 ? 1 : 0);
    ElMessage.success("更新成功");
    getPaperList();
  } catch (error) {
    console.error("更新状态失败：", error);
  }
};

// 查看题目相关
const questionsDialogVisible = ref(false);
const questionList = ref([]);

// 查看题目按钮点击
const handleViewQuestions = async (row) => {
  try {
    const questions = await getPaperQuestions(row.id);
    questionList.value = questions;
    questionsDialogVisible.value = true;
  } catch (error) {
    console.error("获取试卷题目失败：", error);
  }
};

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case "easy":
      return "success";
    case "medium":
      return "warning";
    case "hard":
      return "danger";
    default:
      return "info";
  }
};

onMounted(() => {
  getPaperList();
  getRuleList();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.toolbar-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
